<template>
  <div class="app-container">
    <div class="my-bar">
      <span style="color:red">{{ name }}</span> 权限管理
    </div>
    <el-table v-loading="loading" :data="treeData" row-key="id" default-expand-all border>
      <el-table-column align="left" label="名称" width="190">
        <template slot-scope="scope">
          <!-- <i class="el-icon-plus"/> -->
          <i :class="scope.row.icon" />
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限">
        <template slot-scope="scope">
          <el-checkbox v-if="scope.row.childList && scope.row.childList.length > 0" v-model="scope.row.checkAll" :indeterminate="scope.row.isIndeterminate" style="margin-right:10px" @change="handleCheckAllChange(scope.row)">全选</el-checkbox>
          <!-- <el-checkbox v-for="(child, index) in scope.row.childList" :key="child.id" v-model="scope.row.childList[index].checked" :label="child.name" @change="handleCheck(scope.row, index)" /> -->
          <span v-for="(child, index) in scope.row.childList" :key="child.id" style="margin-right:10px">
            <el-checkbox v-model="scope.row.childList[index].checked" :label="child.name" @change="handleCheck(scope.row, index)" />
            <!-- <i class="el-icon-edit" @click="handlePerm(scope.row, index)" /> -->
            <el-button v-if="scope.row.childList[index].checked" size="mini" icon="el-icon-edit" circle @click="handlePerm(scope.row, scope.row.childList[index], index)" />
          </span>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-button type="primary" @click="$router.push('/role/role')">取消</el-button>
    <el-button :loading="loading" type="success" @click="submit">保存</el-button>

    <!--角色权限-->
    <el-dialog :title="popData.title + ' 的权限配置'" :visible.sync="popData.show">
      <el-form ref="formData" label-width="100" size="small">
        <el-form-item label="请选择权限" required>
          <el-select v-model="permSelect" multiple filterable allow-create default-first-option placeholder="权限列表" style="width:80%">
            <el-option v-for="item in permArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="20">
          注意: {{ popData.router }}:{{ permSelect.join(',') }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="popData.show = false; popData.loading = false">取消</el-button>
        <el-button :loading="popData.loading" size="small" type="primary" @click="onChangePerms">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api, { isAdmin } from '@/api/service'

export default {
  data() {
    return {
      isAdmin: isAdmin(),
      name: '',
      treeData: [{}],
      loading: true,
      loadings: [],
      popData: {
        show: false,
        loading: false,
        title: '',
        router: ''
      },
      permArr: [],
      permSelect: [],
      roleMenuList: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getRoleData(this.$route.query.id)
    },
    getRoleData(id) {
      this.loading = true
      api.getListPage('role.menu', {
        pageSize: 300, showFields: 'id,name,perms,router', showFlags: 'childList[id,name,perms,router]', params: {
          // isRolePerm: true,
          parentId: 0
        }
      }).then(res => {
        this.treeData = res && res.data ? JSON.parse(JSON.stringify(res.data)) : []
        this.treeData.forEach(v => {
          v.checkAll = false
          v.isIndeterminate = false
        })
        api.getListPage('role.role', {
          pageSize: 1, showFields: 'id,name', showFlags: 'roleMenuList[id,roleId,menuId,perms]', params: { id: id }
        }).then(res => {
          var data = res.data[0]
          this.roleMenuList = data.roleMenuList
          if (this.treeData && data.roleMenuList) {
            for (const menu of this.treeData) {
              data.roleMenuList.filter(roleMenu => roleMenu.menuId === menu.id).forEach(roleMenu => {
                this.$set(menu, 'checked', true)
                this.$set(menu, 'roleMenuId', roleMenu.id)
              })
              for (const child of menu.childList) {
                data.roleMenuList.filter(roleMenu => roleMenu.menuId === child.id).forEach(roleMenu => {
                  this.$set(child, 'checked', true)
                  this.$set(child, 'roleMenuId', roleMenu.id)
                })
                // this.handleCheck(child)
              }
              this.handleCheck(menu)
            }
          }
          this.name = data.name
          this.loading = false
        })
      })
    },
    submit() {
      const tempData = {
        id: this.$route.query.id,
        name: this.name,
        roleMenuList: []
      }
      this.treeData.forEach(menu => {
        // 主菜单是否选择
        if (menu.checked || menu.isIndeterminate || menu.checkAll) {
          tempData.roleMenuList.push({
            id: menu.roleMenuId,
            roleId: tempData.id,
            menuId: menu.id
          })
        }
        if (menu.childList) {
          menu.childList.forEach(child => {
            if (child.checked) {
              tempData.roleMenuList.push({
                id: child.roleMenuId,
                roleId: tempData.id,
                menuId: child.id
              })
            }
          })
        }
      })
      this.loading = true
      console.log('tempData===>', tempData)
      api.saveOne('role.role', tempData).then(res => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
        this.$router.push('/role/role')
      })
    },
    handleCheck(item, index) {
      item.checkAll = true
      item.isIndeterminate = false
      item.childList.forEach(elem => {
        if (elem.checked === true) {
          item.isIndeterminate = true
        } else {
          item.checkAll = false
        }
      })
      if (item.checkAll) {
        item.isIndeterminate = false
      }
    },
    handleCheckAllChange(item) {
      item.isIndeterminate = false
      item.childList.forEach(elem => {
        this.$set(elem, 'checked', item.checkAll === true)
      })
    },
    handlePerm(parent, menu, index) {
      console.log('handlePerm', JSON.stringify(menu))
      console.log('this.roleMenuList', JSON.stringify(this.roleMenuList))
      this.permArr = menu.perms.split(',')
      if (this.permArr.length === 0) {
        this.permArr = ['list', 'save']
      }
      if (this.permArr.findIndex(v => v === 'save') < 0) {
        this.permArr.unshift('save')
      }
      if (this.permArr.findIndex(v => v === 'list') < 0) {
        this.permArr.unshift('list')
      }
      // 默认所有权限都有
      if (this.permArr.findIndex(v => v === '*') < 0) {
        this.permArr.unshift('*')
      }
      this.$set(this, 'permSelect', ['*'])
      if (this.roleMenuList) {
        const ind = this.roleMenuList.findIndex(roleMenu => roleMenu.menuId === menu.id)
        if (ind > 0 && this.roleMenuList[ind].perms) {
          this.$set(this, 'permSelect', this.roleMenuList[ind].perms.split(','))
          console.log('this.permSelect', JSON.stringify(this.permSelect))
        }
      }
      this.popData.show = true
      this.popData.menu = menu
      this.popData.title = parent.name + ' > ' + menu.name
      this.popData.router = parent.router + '/' + menu.router
    },
    onChangePerms() {
      console.log('this.popData.menu', this.popData.menu.id, this.popData.menu.roleMenuId)
      if (this.popData.menu && this.popData.menu.roleMenuId) {
        let temp = this.permSelect.join(',')
        if (this.permSelect.findIndex(v => v === '*') > -1) {
          temp = '*'
        }
        this.loading = true
        api.saveOne('role.roleMenu', { id: this.popData.menu.roleMenuId, perms: temp }).then(res => {
          this.loading = false
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.popData.show = false
          const ind = this.roleMenuList.findIndex(roleMenu => roleMenu.menuId === this.popData.menu.id)
          if (ind > 0) {
            this.roleMenuList[ind].perms = temp
          }
        })
      }
    }
  }
}
</script>
